<template>
  <div class="course-score-management">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1>课程成绩管理</h1>
          <div class="user-info">
            <span>欢迎，{{ tutorName }}</span>
            <el-button link @click="logout">退出登录</el-button>
          </div>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="250px" class="sidebar">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="dashboard">
              <el-icon><DataBoard /></el-icon>
              <span>仪表板</span>
            </el-menu-item>
            <el-menu-item index="review-applications">
              <el-icon><Document /></el-icon>
              <span>审核申请</span>
            </el-menu-item>
            <el-menu-item index="scoreboard">
              <el-icon><Trophy /></el-icon>
              <span>奖学金排名</span>
            </el-menu-item>
            <el-menu-item index="course-score-management">
              <el-icon><Edit /></el-icon>
              <span>成绩管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main class="main-content">
          <div class="management-content">
            <!-- 操作栏 -->
            <el-card class="operation-card">
              <div class="operation-bar">
                <el-button type="primary" @click="showAddDialog">
                  <el-icon><Plus /></el-icon>
                  添加成绩
                </el-button>
                <el-button type="success" @click="showBatchImportDialog">
                  <el-icon><Upload /></el-icon>
                  批量导入
                </el-button>
                <div class="search-area">
                  <el-input
                    v-model="searchKeyword"
                    placeholder="搜索学生姓名或学号"
                    style="width: 200px; margin-right: 10px;"
                    clearable
                    @input="handleSearch"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                  <el-select v-model="selectedGrade" placeholder="选择年级" @change="handleSearch" style="width: 120px;">
                    <el-option label="全部年级" value="" />
                    <el-option label="研一" value="研一" />
                    <el-option label="研二" value="研二" />
                    <el-option label="研三" value="研三" />
                  </el-select>
                </div>
              </div>
            </el-card>

            <!-- 成绩列表 -->
            <el-card class="score-list-card">
              <template #header>
                <span>成绩列表</span>
              </template>
              
              <el-table :data="filteredScores" style="width: 100%" v-loading="loading">
                <el-table-column prop="studentId" label="学号" width="120" />
                <el-table-column prop="studentName" label="学生姓名" width="120" />
                <el-table-column prop="grade" label="年级" width="80" />
                <el-table-column prop="courseId" label="课程编号" width="120" />
                <el-table-column prop="courseName" label="课程名称" width="200" />
                <el-table-column prop="score" label="成绩" width="100">
                  <template #default="scope">
                    <span :class="getScoreClass(scope.row.score)">{{ scope.row.score }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="isDegreeCourse" label="学位课程" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.isDegreeCourse ? 'success' : 'info'">
                      {{ scope.row.isDegreeCourse ? '是' : '否' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="scope">
                    <el-button size="small" type="primary" @click="editScore(scope.row)">
                      编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteScore(scope.row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 添加/编辑成绩对话框 -->
    <el-dialog
      v-model="scoreDialogVisible"
      :title="isEdit ? '编辑成绩' : '添加成绩'"
      width="500px"
    >
      <el-form :model="scoreForm" :rules="scoreRules" ref="scoreFormRef" label-width="100px">
        <el-form-item label="学生" prop="studentId">
          <el-select
            v-model="scoreForm.studentId"
            placeholder="选择学生"
            filterable
            style="width: 100%"
            @change="handleStudentChange"
          >
            <el-option
              v-for="student in students"
              :key="student.studentId"
              :label="`${student.name} (${student.studentId})`"
              :value="student.studentId"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程编号" prop="courseId">
          <el-input v-model="scoreForm.courseId" placeholder="请输入课程编号" />
        </el-form-item>
        
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="scoreForm.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        
        <el-form-item label="成绩" prop="score">
          <el-input-number
            v-model="scoreForm.score"
            :min="0"
            :max="100"
            :precision="1"
            style="width: 100%"
            placeholder="请输入成绩"
          />
        </el-form-item>
        
        <el-form-item label="学位课程" prop="isDegreeCourse">
          <el-switch
            v-model="scoreForm.isDegreeCourse"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scoreDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitScore" :loading="submitting">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="batchImportDialogVisible"
      title="批量导入成绩"
      width="600px"
    >
      <div class="batch-import-content">
        <el-alert
          title="导入说明"
          description="请按照模板格式准备Excel文件，包含学号、课程编号、课程名称、成绩、是否学位课程等字段"
          type="info"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 xlsx/xls 文件，且不超过 10MB
            </div>
          </template>
        </el-upload>
        
        <div class="template-download">
          <el-button type="text" @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载导入模板
          </el-button>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchImportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="importScores" :loading="importing">
            开始导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  DataBoard, Document, Trophy, Edit, Plus, Upload, Search,
  UploadFilled, Download
} from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const activeMenu = ref('course-score-management')
const tutorName = ref(localStorage.getItem('name') || '导师')
const loading = ref(false)
const submitting = ref(false)
const importing = ref(false)

// 数据
const scores = ref([])
const students = ref([])
const searchKeyword = ref('')
const selectedGrade = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 对话框
const scoreDialogVisible = ref(false)
const batchImportDialogVisible = ref(false)
const isEdit = ref(false)
const scoreFormRef = ref()
const fileList = ref([])

// 表单数据
const scoreForm = ref({
  scoreId: '',
  studentId: '',
  courseId: '',
  courseName: '',
  score: null,
  isDegreeCourse: false
})

// 表单验证规则
const scoreRules = {
  studentId: [
    { required: true, message: '请选择学生', trigger: 'change' }
  ],
  courseId: [
    { required: true, message: '请输入课程编号', trigger: 'blur' }
  ],
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  score: [
    { required: true, message: '请输入成绩', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '成绩必须在0-100之间', trigger: 'blur' }
  ]
}

// 计算属性
const filteredScores = computed(() => {
  let result = scores.value
  
  if (searchKeyword.value) {
    result = result.filter(score => 
      score.studentName?.includes(searchKeyword.value) ||
      score.studentId?.includes(searchKeyword.value)
    )
  }
  
  if (selectedGrade.value) {
    result = result.filter(score => score.grade === selectedGrade.value)
  }
  
  return result
})

// 方法
const handleMenuSelect = (index) => {
  if (index === 'dashboard') {
    router.push('/professor/dashboard')
  } else if (index === 'review-applications') {
    router.push('/professor/review-applications')
  } else if (index === 'scoreboard') {
    router.push('/professor/scoreboard')
  } else if (index === 'course-score-management') {
    router.push('/professor/course-score-management')
  }
}

const logout = () => {
  localStorage.clear()
  router.push('/login')
}

const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 70) return 'score-average'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

const loadScores = async () => {
  loading.value = true
  try {
    const response = await axios.get('/course-scores')
    const scoresData = response.data
    
    // 获取学生信息以补充姓名和年级
    const studentsResponse = await axios.get('/students')
    const studentsMap = new Map()
    studentsResponse.data.forEach(student => {
      studentsMap.set(student.studentId, student)
    })
    
    // 补充学生信息
    scores.value = scoresData.map(score => {
      const student = studentsMap.get(score.studentId)
      return {
        ...score,
        studentName: student ? student.name : '未知学生',
        grade: student ? student.grade : '未知年级'
      }
    })
    
    total.value = scores.value.length
  } catch (error) {
    console.error('加载成绩数据失败:', error)
    ElMessage.error('加载成绩数据失败')
  } finally {
    loading.value = false
  }
}

const loadStudents = async () => {
  try {
    const response = await axios.get('/students')
    students.value = response.data
  } catch (error) {
    console.error('加载学生数据失败:', error)
    ElMessage.error('加载学生数据失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const showAddDialog = () => {
  isEdit.value = false
  scoreForm.value = {
    scoreId: '',
    studentId: '',
    courseId: '',
    courseName: '',
    score: null,
    isDegreeCourse: false
  }
  scoreDialogVisible.value = true
}

const editScore = (row) => {
  isEdit.value = true
  scoreForm.value = { ...row }
  scoreDialogVisible.value = true
}

const handleStudentChange = (studentId) => {
  const student = students.value.find(s => s.studentId === studentId)
  if (student) {
    // 可以在这里设置一些默认值
  }
}

const submitScore = async () => {
  if (!scoreFormRef.value) return
  
  try {
    await scoreFormRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await axios.put(`/course-scores/${scoreForm.value.scoreId}`, scoreForm.value)
      ElMessage.success('成绩更新成功')
    } else {
      scoreForm.value.scoreId = Date.now().toString() // 简单的ID生成
      await axios.post('/course-scores', scoreForm.value)
      ElMessage.success('成绩添加成功')
    }
    
    scoreDialogVisible.value = false
    loadScores()
  } catch (error) {
    console.error('提交成绩失败:', error)
    ElMessage.error('提交成绩失败')
  } finally {
    submitting.value = false
  }
}

const deleteScore = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生 ${row.studentName} 的 ${row.courseName} 成绩吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await axios.delete(`/course-scores/${row.scoreId}`)
    ElMessage.success('删除成功')
    loadScores()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除成绩失败:', error)
      ElMessage.error('删除成绩失败')
    }
  }
}

const showBatchImportDialog = () => {
  batchImportDialogVisible.value = true
  fileList.value = []
}

const handleFileChange = (file) => {
  fileList.value = [file]
}

const downloadTemplate = () => {
  // 这里可以实现模板下载功能
  ElMessage.info('模板下载功能开发中...')
}

const importScores = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }
  
  importing.value = true
  try {
    // 这里实现文件上传和解析逻辑
    ElMessage.success('批量导入功能开发中...')
    batchImportDialogVisible.value = false
  } catch (error) {
    console.error('批量导入失败:', error)
    ElMessage.error('批量导入失败')
  } finally {
    importing.value = false
  }
}

onMounted(() => {
  loadScores()
  loadStudents()
})
</script>

<style scoped>
.course-score-management {
  height: 100vh;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-content h1 {
  margin: 0;
  font-size: 20px;
}

.sidebar {
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
  background-color: #f5f7fa;
}

.management-content {
  max-width: 1200px;
  margin: 0 auto;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-area {
  display: flex;
  align-items: center;
}

.score-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-average {
  color: #e6a23c;
  font-weight: bold;
}

.score-pass {
  color: #909399;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}

.batch-import-content {
  padding: 20px 0;
}

.template-download {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 